//
//  MBImageGalleryView.m
//  MobellCloud_ios
//
//  Created by cherry pu on 2018/1/22.
//  Copyright © 2018年 zhangXin. All rights reserved.
//

#import "MBImageGalleryView.h"
#import "MBScaledImageView.h"

@interface MBImageGalleryView ()<UIScrollViewDelegate>
@property (nonatomic,weak)      UIPageControl * pageControl;
@property (nonatomic,weak)      UIScrollView * galleryScrollView;
@property (nonatomic,assign)    CGFloat edgeOffset;
@property (nonatomic,weak)      UIView * containView;
@property (nonatomic,assign)    int lastPage;
@property (nonatomic,strong)    UIImage * defaultImage;
@property (nonatomic,assign)    NSInteger selectedIndex;
@property (nonatomic,weak)      UILabel * noticeLabel;

@end

@implementation MBImageGalleryView

- (instancetype)initWithEdgeOffset:(CGFloat)edgeOffset
{
    if(self = [super init]){
        self.edgeOffset = edgeOffset;
    }
    return self;
}


- (void)setDataSource:(id<MBImageGalleryViewDataSource>)dataSource
{
    _dataSource = dataSource;
    
    [self setupScrollView];
}



#pragma mark - 组件初始化
- (void)setupScrollView
{
    if([self.dataSource respondsToSelector:@selector(sourceImageItemArrayForGallery)]){
        self.imageItemArray = [self.dataSource sourceImageItemArrayForGallery];
    }else{
        return;
    }
    
    UIScrollView * galleryScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(-self.edgeOffset, 0, SCREEN_WIDTH + self.edgeOffset, SCREEN_HEIGHT)];
    galleryScrollView.delegate = self;
    galleryScrollView.bounces = YES;
    galleryScrollView.pagingEnabled = YES;
    galleryScrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:galleryScrollView];
    
    galleryScrollView.contentSize = CGSizeMake((SCREEN_WIDTH + self.edgeOffset) * self.imageItemArray.count, SCREEN_HEIGHT);
    self.galleryScrollView = galleryScrollView;
    
    UIView * containView = [[UIView alloc]init];
    [galleryScrollView addSubview:containView];
    self.containView = containView;
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(galleryScrollView).with.insets(UIEdgeInsetsZero);
    }];
    
    UIView * previousView = nil;
    for (int i = 0;i<self.imageItemArray.count;i++) {
        NSString*  imageUrl;
        if ([self.imageItemArray[i] isKindOfClass:[NSString class]]) {
            imageUrl = self.imageItemArray[i];
        }
        if (![imageUrl containsString:@"http"]) {
            imageUrl = [NSString stringWithFormat:@"%@%@",BASE_IMAGE_URL,imageUrl];
        }
        MBScaledImageView * scaledImageView = [[MBScaledImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        
        [containView addSubview:scaledImageView];
        [scaledImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            if(previousView){
                make.left.equalTo(previousView.mas_right).with.offset(self.edgeOffset);
            }else{
                make.left.equalTo(containView).with.offset(self.edgeOffset);
            }
            make.top.equalTo(containView);
            make.size.mas_equalTo([UIScreen mainScreen].bounds.size);
        }];
        previousView = scaledImageView;
        
        UIImage* image = [[MBCacheService sharedInstance]fetchBannerImageWithUrl:imageUrl];
        
        
        if(image){
            scaledImageView.contentImage = image;
        }else{
            scaledImageView.contentImage = self.defaultImage;
            
            [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageDownloaderLowPriority progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                if(image){
                    scaledImageView.contentImage = image;
                    [[MBCacheService sharedInstance]cacheBannerImageWithUrl:imageUrl andImage:image];
                }
                [[SDImageCache sharedImageCache] clearMemory];

            }];
        }
        
        if(i == self.imageItemArray.count - 1){
            [containView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.bottom.equalTo(previousView);
            }];
        }
    }
    
    
    UILabel * noticeLabel = [[UILabel alloc] init];
    noticeLabel.textColor = [UIColor whiteColor];
    noticeLabel.font = [UIFont lf_systemFontOfSize:12];
    noticeLabel.text = [NSString stringWithFormat:@"%d/%d",(int)self.selectedIndex+1,(int)self.imageItemArray.count];
    noticeLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:noticeLabel];
    self.noticeLabel = noticeLabel;
    
    [noticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).with.offset(- [UIView lf_sizeFromIphone6:20]);
        make.centerX.equalTo(self);
    }];
    
    if(self.imageItemArray.count > 1){
        //        UIPageControl * pageControl = [[UIPageControl alloc]init];
        //        pageControl.currentPageIndicatorTintColor = MainColor(1);
        //        pageControl.numberOfPages = self.imageItemArray.count;
        //        self.pageControl = pageControl;
        //        [self addSubview:pageControl];
        //        [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.bottom.equalTo(self);
        //            make.centerX.equalTo(self);
        //        }];
    }
}


#pragma mark - 定位到index对应的image
- (void)setImagePositionIndex:(NSInteger)index
{
    if(self.imageItemArray.count > 0){
        //处理越界问题
        if(index < 0){
            index = 0;
        }
        if(index > self.imageItemArray.count - 1){
            index = self.imageItemArray.count - 1;
        }
        [self.galleryScrollView setContentOffset:CGPointMake((SCREEN_WIDTH + self.edgeOffset) * index, 0)];
    }
}

#pragma mark - lazy load
- (UIImage *)defaultImage
{
    if(_defaultImage == nil){
        _defaultImage = [UIImage imageFromColor:[UIColor colorWithRed: 15 / 255.0 green:15 / 255.0 blue:15 / 255.0 alpha:1.0] forSize:CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH) withCornerRadius:0];
    }
    return _defaultImage;
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat xOffset = scrollView.contentOffset.x;
    int page = xOffset / ([UIScreen mainScreen].bounds.size.width) + 0.5;
    self.currentIndex = page;
    //    self.pageControl.currentPage = page;
    if(page + 1 <= self.imageItemArray.count){
        self.noticeLabel.text = [NSString stringWithFormat:@"%d / %d",page+1,(int)self.imageItemArray.count];
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int currentPage = (int)self.pageControl.currentPage;
    if(currentPage != self.lastPage){
        for (MBScaledImageView * scaledImageView in self.containView.subviews) {
            if([scaledImageView isKindOfClass:[MBScaledImageView class]]){
                [scaledImageView resetZoomScale];
            }
        }
    }
    self.lastPage = currentPage;
}


@end
